package com.well.rpc.netty;

import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.net.ssl.SSLException;
import java.io.File;

/**
 * <p>
 * ssl context config
 * </p>
 *
 * @author weedo
 * @since 2022/8/24
 */

public class ClientSsl {
    private SslContext sslCtx = null;
    private Boolean enableSsl;

    public void setSslCtx(boolean enableSsl, String certPath, String keyPath, String caPath) {
        this.enableSsl = enableSsl;
        if (!enableSsl) {
            return;
        }
        Assert.isTrue(StringUtils.isNoneBlank(certPath), "certPath is not null.");
        Assert.isTrue(StringUtils.isNoneBlank(keyPath), "keyPath is not null.");
        Assert.isTrue(StringUtils.isNoneBlank(caPath), "caPath is not null.");
        File serverCert = new File(certPath);
        File serverKey = new File(keyPath);
        File rootFile = new File(caPath);
        try {
            sslCtx = SslContextBuilder.forServer(serverCert, serverKey).trustManager(rootFile).clientAuth(ClientAuth.REQUIRE).build();
        } catch (SSLException e) {
            e.printStackTrace();
        }
    }

    public SslContext getSslContext() {
        return sslCtx;
    }

    public Boolean getEnableSsl() {
        return enableSsl;
    }
}
